package com.wxtech.heartbeat.util;

import org.apache.log4j.Logger;

//import com.wxtech.heartbeat.Config;
import com.wxtech.heartbeat.Context;
//import com.wxtech.heartbeat.database.DataManager;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;


public class RedisUtil {

	private static Logger logger = Logger.getLogger(RedisUtil.class);
	private static volatile RedisUtil redisInstance = null;

	private JedisPool jedisPool;

	
	private RedisUtil() {
		initJedisPool();
		logger.debug("init redis pool done.");
    }


	public static RedisUtil getInstance() {
		synchronized(RedisUtil.class) {
			if(redisInstance == null) {
				redisInstance = new RedisUtil();				
			}
		}
		return redisInstance;
	}
	
    /**
     * 初始化JedisPool
     */
    private void initJedisPool() {
//    	DataManager dataManager = Context.getDataManager();

    		JedisPoolConfig config = new JedisPoolConfig();
    		config.setTestOnBorrow(true);
        jedisPool = new JedisPool(
                config,
                Context.getConfig().getString("redis_ip"), 
                Context.getConfig().getInteger("redis_port"));
        
    }

    /**
     * 通用方法：从JedisPool中获取Jedis
     *
     * @return
     */
    private Jedis getJedis() {
        if (jedisPool == null) {
            initJedisPool();
        }
        return jedisPool.getResource();
    }

	private void releaseJedis(Jedis jedis) {
		if(jedis != null) {
			jedisPool.returnResource(jedis);
		}
	}
	
	public void publishRedis(String json) {
		Jedis jedis = getJedis();
		String chel = Context.getConfig().getString("redis_publish_channel", "json");
		jedis.publish(chel, json);
		releaseJedis(jedis);
	}
}
